<?php namespace models;
use helpers\Helper as Helper;
/**
 * This code is property of Piotr Poradzisz. Do not distribute under threat of legal consequences.
 * All rights reserved.
 * Все права защищены.
 * Alle Rechte vorbehalten.
 * Todos los derechos reservados.
 * Wszelkie prawa zastrzeżone.
 *                  جميع الحقوق محفوظة
 * 保留所有权利
 * すべての著作権
 * @author Piotr Poradzisz
 * email: piotr.poradzisz@gmail.com
 * tel.: +48668027020
 */
class Form extends Field{
    public function getFormRights($menu = null)
    {
        if(!$menu)
        {
            $menu = $_SESSION['navigation']['menu'];            
        }
        $mysql = new Mysql();
        $query = "SELECT fr.* FROM menu m JOIN (formRights fr) ON (m.formRights = fr.id) WHERE m.id = $menu";
        return $mysql->getRow($query);
    }

    public function getFormPart($field) {
        if($field['fieldTag'] == 'select' or $field['fieldType'] == 'radio')
        {
            if($field['params'] == 'tree')
            {
                $options = Helper::getDictionaryValues($field['tableName'], null, true);
            }
            else
            {
                $options = Helper::getDictionaryValues($field['tableName'], null, false);
            }
            $field['options'] = $options;
        }
        else if($field['referenceTable'])
        {
            if($field['fieldType'] == 'file')
            {
                $file = new File();
                $field['fileTypes'] = $file->getFileTypes(null, $field['fieldId']);
            }
        }
        return $field;
    }

    public function addFormPart($fieldId, $itemId = null)
    {
        $menu = $_SESSION['navigation']['menu'];
        $fields = self::getFields($menu, "f.id = $fieldId AND fr.display");
        $field = $this->getFormPart($fields[0]);
        if($itemId != null)
        {
            $field = $this->getFieldValue($field, $itemId);
        }
        return $field;
    }


    public function getFieldValue($field, $itemId)
    {

        if(!$field['referenceTable'])
        {
            $mysql = new Mysql();
            $relation = new Relation($_SESSION['navigation']['menu']);
            $fields[0] = $field;
            $relation->select($fields);
            $select =   $_SESSION['query']['select'];
            $from   =   $_SESSION['query']['from'];
            $join   =   $_SESSION['query']['join'];
            $where  = " WHERE   $from.id = $itemId ";
            $query  = " SELECT  $select
                        FROM    $from
                                $join
                                $where  ";
            $value = $mysql->getRecord($query);
        }

        if($field['referenceTable'])
        {
            if($field['fieldType'] == 'file')
            {
                $file = new File();
                $field['files'] = $file->read(null, $itemId, $field['fieldId']);
            }
            else if($field['fieldTag'] == 'select')
            {
                $select = new Select();
                $field['values'] = $select->read($field['fieldId'], $itemId);
            }
        }
        else{
            if(!$field['tableName'])
            {
                $field['value'] =  $value;
            }
            else
            {
                if($field['fieldTag'] == 'select' or $field['fieldType'] == 'radio')
                {
                    $key = Helper::multiDimensionalSearch($field['options'], 'name', $value);
                    $field['valueId'] = $field['options'][$key]['id'];
                }
                
                $field['value'] =  $value;
            }
        }
        return $field;
    }

    public function removeFormPart($fieldId)
    {
        $menu = $_SESSION['navigation']['menu'];
        $fields = self::getFields($menu, "f.id = $fieldId AND fr.display");
        return $fields[0];
    }

    public function getFormRows($id = null){
        $mysql = new Mysql();
        $menu = $_SESSION['navigation']['menu'];

        if($_SESSION['navigation']['formSequence'] == 1 and $id) $fields = self::getFields($menu, 'fr.display', $id);
        else $fields = self::getFields($menu, 'fr.display');
        
        foreach($fields as $key => $value) $fields[$key] = $this->getFormPart($value);

        if($id){
            $relation = new Relation($_SESSION['navigation']['menu']);
            $relation->select($fields);
            $select =   $_SESSION['query']['select'];
            $from   =   $_SESSION['query']['from'];
            $join   =   $_SESSION['query']['join'];
            $where  =   " WHERE $from.id = $id ";

            $query = "  SELECT  $select
                        FROM    $from
                                $join
                                $where  ";
            $row = $mysql->getRow($query);
        }

        foreach($fields as $fieldKey => $field){
            if($id){
                if($field['referenceTable']){
                    if($field['fieldType'] == 'file'){
                        $file = new File();
                        $fields[$fieldKey]['files'] = $file->read(null, $id, $field['fieldId']);
                    }
                    else if($field['fieldTag'] == 'select'){
                        $select = new Select();
                        $fields[$fieldKey]['values'] = $select->read($field['fieldId'], $id);
                    }
                }
                else{
                    if(!$field['tableName']){
                        
                        if($field['fieldType'] == 'file')
                        {
                            $file = new File();
                            $fields[$fieldKey]['files'] = $file->read(null, $id, $field['fieldId']);
                        }
                        else
                        {
                            $fields[$fieldKey]['value'] = $row[$field['fieldId']];
                        }    
                        
                    }
                    else{
                        if($field['fieldTag'] == 'select' or $field['fieldType'] == 'radio'){
                            $key = Helper::multiDimensionalSearch($field['options'], 'name', $row[$field['fieldId']]);
                            $fields[$fieldKey]['valueId'] = $field['options'][$key]['id'];
                        }
                        $fields[$fieldKey]['value'] = $row[$field['fieldId']];
                    }
                }

            }
            if($_SESSION['navigation']['detailsDisplay'] == 1 or $_SESSION['navigation']['listDisplay'] == 1){
                if($field['control'] == 1)  $control[] = $fields[$fieldKey];
                else if(!$id or (!$field['detailsDisplay'] and !$field['listDisplay'])) $inactive[] = $fields[$fieldKey];
                else $content[] = $fields[$fieldKey];
            }
            else{
                if($field['control'] == 1)  $control[] = $fields[$fieldKey];
                else $content[] = $fields[$fieldKey];  
            }                      
        }
        
        unset($fields);
        $fields['content'] = $content;
        $fields['control'] = $control;
        $fields['inactive'] = $inactive;
        return $fields;
    }

    public function update($post){
        $mysql = new Mysql();
        $id = $post['itemId'];
        $from = $_SESSION['query']['from'];
        unset($post['itemId']);
        $set  = $this->setSet($post);
        echo $query = "UPDATE $from SET $set WHERE id = $id";
        $mysql->setQuery($query);
    }

    public function create($post){
        $mysql = new Mysql();
        $into = $_SESSION['query']['from'];
        $insert  = $this->setInsert($post);
        $query = "INSERT INTO $into $insert";
        $mysql->setQuery($query);
    }

    public function delete($id){
        $menu = $_SESSION['navigation']['menu'];
        $from = $_SESSION['query']['from'];
        $fields = self::getFields($menu, 'fr.display');
        $file = new File();
        foreach($fields as $fileldKey => $field){
            if($field['fieldType'] == 'file'){
                $file->delete($id, $field['fieldId'], true);
            }
        }
        $mysql = new Mysql();
        $from = $_SESSION['query']['from'];
        $query = "DELETE FROM $from WHERE id = $id";
        $mysql->setQuery($query);
    }

    public function multiDelete($ids){
        foreach($ids as $id){
            $this->delete($id);
        }
    }

    private function setInsert($post){
        $from = $_SESSION['query']['from'];
        $columns = array();
        $values = array();
        foreach($post as $dataTableKey => $dataTable){
            if($dataTable['type'] == 'password') $dataTable['value'] = md5($dataTable['value']);
            $value = mysql_escape_string($dataTable['value']);
            array_push($values, "'$value'");
            if(!$dataTable['referenceTable']){
                $tableName = $from;
                if(!$dataTable['tableName']){
                    $columnName = $dataTable['columnName'];
                }
                else{
                    $columnName = $dataTable['tableName'];
                }
            }
            else{
                // this propably doesn't work...
                $columnName = $dataTable['columnName'];
                $tableName = $dataTable['referenceTable'];
            }
            array_push($columns, "$tableName.$columnName");
        }
        $columns = implode(', ', $columns);
        $values = implode(', ', $values);
        $insert = "($columns) VALUES ($values)";
        return $insert;
    }

    private function setSet($post){
        $from = $_SESSION['query']['from'];
        $set = array();
        foreach($post as $fieldId => $value){
            $this->setFieldProperties($fieldId, array('referenceTable', 'tableName', 'name', 'fieldType'));
            if($this->fieldType == 'password')  $value = md5($value);
            $value = mysql_escape_string($value);
            if(!isset($this->referenceTable)){
                $tableName = $from;
                if(!$this->tableName){
                    $columnName = $this->name;
                }
                else{
                    if($this->tableName == $from) $columnName = $this->name;
                    else $columnName = $this->tableName;
                }
            }
            else{
                // this propably doesn't work...
                $columnName = $this->name;
                $tableName = $this->referenceTable;
            }
            if($value == '')  array_push($set, "$tableName.$columnName = null");
            else array_push($set, "$tableName.$columnName = '$value'");
        }
        $set = implode(', ', $set);
        return $set;
    }

    public function setFormSequence($fieldId, $sequence){
        $this->setFieldProperties($fieldId, array('referenceTable'));
        $this->setSequence($this->referenceTable, $sequence);
    }
}
?>